package com.alogic.cert.bc;

import org.bouncycastle.asn1.x509.KeyPurposeId;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;


/**
 * KeyPurposeIdTools
 *
 * @since 1.6.13.40 [20210306 duanyy] <br>
 */
public class KeyPurposeIdTools {
    private static Map<String, KeyPurposeId> nameIndex = new HashMap<String,KeyPurposeId>();
    private static Map<String,KeyPurposeId> idIndex = new HashMap<String,KeyPurposeId>();
    private static Map<String,String> idName = new HashMap<String,String>();

    public static KeyPurposeId getByName(String name){
        return nameIndex.get(name);
    }

    public static KeyPurposeId getById(String id){
        return idIndex.get(id);
    }

    public static String getName(String id){
        return idName.get(id);
    }

    static {
        Class<KeyPurposeId> clazz = KeyPurposeId.class;
        Field[] fields = clazz.getDeclaredFields();
        for (Field field:fields){
            int modifiers = field.getModifiers();

            if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)){
                try {
                    Object obj = field.get(clazz);
                    if (obj instanceof KeyPurposeId) {
                        KeyPurposeId kpId = (KeyPurposeId)obj;
                        nameIndex.put(field.getName(), kpId);
                        idIndex.put(kpId.getId(), kpId);
                        idName.put(kpId.getId(), field.getName());
                    }
                } catch (IllegalAccessException e) {
                    continue;
                }
            }
        }
    }
}
